package c16多线程;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//@1实现Callable接口——类似于Runnable接口，但是call方法有返回值！
class CallThread implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {
		int i = 0;
		for (; i < 100; i++) {
			System.err.println(Thread.currentThread().getName() + "--" + i);
		}
		return i;
	}
}

//可以不用指定泛型类型！call的返回值就变成了Object类型了。
class C implements Callable {

	@Override
	public Object call() throws Exception {
		//TODO Auto-generated method stub
		return null;
	}
}

public class Callable和FutureTask {

	public static void main(String[] args) {
		//@2创建CallThread对象
		CallThread ct = new CallThread();
		//@3使用FutureTask来包装CallThread对象。注意泛型使用：
		FutureTask<Integer> ft = new FutureTask<>(ct);
		for (int i = 0; i < 100; i++) {
			System.err.println(Thread.currentThread().getName() + "--" + i);
			if (i == 10) {
				//@4使用FutureTask作为target创建子线程并启动
				new Thread(ft, "有返回值的线程").start();
			}
		}

		try {
			//@5调用FutureTask的方法获取返回值，调用时会阻塞主线程，直到call方法结束并返回为止！
			System.err.println("子线程的返回值：" + ft.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			//TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}